<template>
  <div>
    <!-- @select事件：点击索引栏的字符时触发 handleSelect不带小括号，会自动传递索引参数-->
    <van-index-bar :index-list="computeCitiesList" @select="handleSelect">
      <div v-for="(city, idx) in citiesList" :key="idx">
        <!-- 侧边导航栏 -->
        <van-index-anchor :index="city.letter" class="city-letter" />
        <van-cell
          v-for="cityname in city.list"
          :key="cityname.cityId"
          :title="cityname.name"
          @click="handlePickCity(cityname.cityId, cityname.name)"
        />
      </div>
    </van-index-bar>
  </div>
</template>
<script>
import http from "@/utils/http.js";
import { IndexBar, IndexAnchor, Toast } from "vant";
import Vue from "vue";
import { mapState, mapMutations } from "vuex";
Vue.use(IndexBar).use(IndexAnchor).use(Toast);
export default {
  data() {
    return {
      citiesList: [],
    };
  },
  computed: {
    ...mapState("cityModule", ["cityId", "cityName"]),
  },
  methods: {
    ...mapMutations("cityModule", ["setCityId", "setCityName"]),
    ...mapMutations("cinemaModule", ["setCinemaData"]),
    formatData(cities) {
      let letterList = []; // 26个大写字母
      for (let i = 65; i < 91; i++) {
        letterList.push(String.fromCharCode(i));
      }
      letterList.forEach((letter) => {
        let list = cities.filter(
          (item) => item.pinyin.substr(0, 1).toUpperCase() === letter
        ); // 存储每个字母对应的城市
        if (list.length) {
          // 最后需要的数组
          this.citiesList.push({
            letter,
            list,
          });
        }
      });
      console.log(this.citiesList);
    },
    handleSelect(index) {
      Toast(index);
    },
    handlePickCity(id, name) {
      this.setCinemaData([]); // 必须清空原数组
      this.setCityId(id);
      this.setCityName(name);
      // console.log(this.$store.state.cityId, this.$store.state.cityName);
      this.$router.back();
    },
  },
  computed: {
    computeCitiesList() {
      return this.citiesList.map((item) => item.letter);
    },
  },
  mounted() {
    http({
      url: `/gateway?k=7662164`,
      headers: {
        "X-Host": "mall.film-ticket.city.list",
      },
    }).then((res) => {
      this.formatData(res.data.data.cities);
    });
  },
};
</script>

<style>
.van-index-anchor {
  background-color: #ccc;
}
.van-index-anchor--sticky {
  background-color: #fff;
}
</style>